package com.rzico.sbl.ui.order

import android.widget.CompoundButton
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityDeliverBatchBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.OrderData
import com.rzico.sbl.other.privacyStatus
import com.rzico.sbl.other.userRole
import com.rzico.sbl.viewmodel.DeliverViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.phoneReplaceWithStar
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.count
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.*
import com.xinnuo.slimadapter.SlimAdapter

class DeliverBatchActivity : BaseActivity(R.layout.activity_deliver_batch) {

    private val mBinding by lazy { ActivityDeliverBatchBinding.bind(getRootView()) }

    override fun getViewModel() = get<DeliverViewModel>()

    override fun initData() {
        initTitle(title = "我的运单")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .batchAll
            .setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.address_default_selector
            )

        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .also {
                        it.emptyImg.setEmptyImage(
                            resId = R.mipmap.icon_order_no,
                            dpSize = 100f
                        )
                        it.emptyHint.text = "暂无相关运单信息！"
                    }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration())

                    mAdapter = SlimAdapter.creator()
                        .register<OrderData>(R.layout.item_deliver_batch) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_batch_time, bean.orderDate.getTimeString())
                                text(
                                    R.id.item_batch_name,
                                    "${bean.consignee}  ${
                                        when {
                                            userRole in "1,2" 
                                                    || privacyStatus == "off" -> bean.phone
                                            else -> bean.phone.phoneReplaceWithStar()
                                        }
                                    }"
                                )
                                text(R.id.item_batch_adress, bean.address)
                                text(R.id.item_batch_num, bean.orderSn)
                                text(
                                    R.id.item_batch_send,
                                    "${bean.adminName}${bean.adminPhone.ifNotEmpty { " - $it" }}"
                                )

                                image(
                                    R.id.item_batch_check,
                                    conditionIf(
                                        bean.check,
                                        R.mipmap.login_yes_orange,
                                        R.mipmap.login_no
                                    )
                                )

                                clicked(R.id.item_batch_check) {
                                    bean.check = !bean.check
                                    notifyItemChanged(index)

                                    checkAllSelected()
                                }

                                clicked(R.id.item_batch) {
                                    startActivityEx<DeliverDetailActivity>(
                                        "orderSn" to bean.orderSn,
                                        "shippingSn" to bean.sn,
                                        "status" to "dispatch",
                                        "shipId" to bean.id
                                    )
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    override fun initListener() {
        mBinding.apply {
            batchAll.oneTouch(handle = { mList.isEmpty() })
            batchAll.setOnCheckedChangeListener(this@DeliverBatchActivity)

            batchClear.oneClick {
                mList
                    .any { (it as OrderData).check }
                    .condition {
                        mList.forEach { (it as OrderData).check = false }
                        mAdapter.notifyDataSetChanged()

                        checkAllSelected()
                    }
            }

            batchSend.oneClick {
                mList.notEmpty {
                    when {
                        any { (it as OrderData).check } -> {
                            if (filter { (it as OrderData).check }.count() > 40) {
                                showToast("批量送达每次操作不超过40条")
                                return@oneClick
                            }

                            showHintDialog(
                                title = "批量送达",
                                hint = "确定要进行批量送达操作吗？",
                                onSure = {
                                    val idList = filter { (it as OrderData).check }
                                        .map { (it as OrderData).id }

                                    getViewModel()
                                        .requestBind(
                                            requestUrl = BaseUrl.deliveryBth,
                                            params = arrayOf(
                                                "ids" to idList.joinToString(",")
                                            )
                                        )
                                        .bindLifeCycle(getLifecycleOwner())
                                        .subscribeBySuccess(
                                            event = getViewModel(),
                                            onSuccess = {
                                                showToast("批量送达成功！")

                                                updateList()

                                                // 更新运单列表
                                                LiveEventBus
                                                    .get("deliverList")
                                                    .post("refresh")
                                            }
                                        )
                                }
                            )
                        }
                        else -> showToast("请选择要送达的运单")
                    }
                }
            }
        }

        observe<String>("batchList") {
            getViewModel()
                .delay { updateList() }
        }
    }

    /**
     * 全选点击事件监听
     */
    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mList.forEach { (it as OrderData).check = isChecked }
        mAdapter.notifyDataSetChanged()

        mBinding.batchSend.text = "批量送达(${totalCount()})"
    }

    /**
     * 检查全选按钮状态
     */
    private fun checkAllSelected() {
        mBinding.apply {
            batchAll.setOnCheckedChangeListener(null)

            batchAll.isChecked = mList.isNotEmpty()
                    && mList.none { !(it as OrderData).check }

            batchAll.setOnCheckedChangeListener(this@DeliverBatchActivity)

            batchSend.text = "批量送达(${totalCount()})"
        }
    }

    /**
     * 选中数量
     */
    private fun totalCount() = mList.count { (it as OrderData).check }

    /**
     * 运单列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .batchList(
                page = index,
                state = "dispatch",
                onSuccess = {
                    mList.apply {
                        (index == 0).condition {
                            clear()
                            pageNum = 0
                        }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    checkAllSelected()

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh
                                .isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 列表数据刷新
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh
                    .isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}